package com.in.utils;

import java.util.Random;

/**
 * @PackageName: java.entity
 * @ClassName: RandomValueUtil
 * @Description: 随机数，随机字符串工具类
 * @Author: liulianjia
 * @Date: 2020/11/9 23:15
 */
public class RandomValueUtil {
    public static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String LETTER_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String NUMBER_CHAR = "0123456789";

    /**
     * 产生len长度的随机字符串
     * @param len
     * @return
     */
    public static String generateStr(int len){
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i <len ; i++) {
            sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * @Author liulianjia
     * @Description 产生len长度的随机数字
     * @Date 2024/12/3 17:09
     **/
    public static String generateNum(int len){
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i <len ; i++) {
            sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 返回一个定长的随机纯字母字符串(只包含大小写字母)
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateMixStr(int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(LETTER_CHAR.charAt(random.nextInt(LETTER_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 返回一个定长的随机纯大写字母字符串(只包含小写字母)
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateLowerStr(int length) {
        return generateMixStr(length).toLowerCase();
    }

    /**
     * 返回一个定长的随机纯小写字母字符串(只包含大写字母)
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateUpperStr(int length) {
        return generateMixStr(length).toUpperCase();
    }

    /**
     * 生成一个定长的纯0字符串
     * @param length 字符串长度
     * @return 纯0字符串
     */
    public static String generateZeroStr(int length) {
        return "0".repeat(Math.max(0, length));
    }

    /**
     * 根据数字生成一个定长的字符串，长度不够前面补0
     * @param num       数字
     * @param fixedLength 字符串长度
     * @return 定长的字符串
     */
    public static String toFixedLengthStr(long num, int fixedLength) {
        StringBuilder sb = new StringBuilder();
        String strNum = String.valueOf(num);
        if (fixedLength - strNum.length() >= 0) {
            sb.append(generateZeroStr(fixedLength - strNum.length()));
        } else {
            throw new RuntimeException("将数字" + num + "转化为长度为" + fixedLength + "的字符串发生异常！");
        }
        sb.append(strNum);
        return sb.toString();
    }

}
